package com.le.ui;

import com.le.component.BackGroundPanel;
import com.le.component.MyTabbedPaneUI;
import com.le.util.Query;
import com.le.util.RandomAdd;
import com.le.util.ScreenUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

public class ManageInterface {
    String userName;
    JFrame jFrame;
    JTabbedPane jTabbedPane;
    String hostIpAddress;
    final int WIDTH = 1080;
    final int HEIGHT = 720;

    JSplitPane classManageSplitPane = new JSplitPane();
    JSplitPane gradeManageSplitPane = new JSplitPane();
    JPanel studentTablePanel = new JPanel();


    public ManageInterface(String userName) {
        this.userName = userName;
    }

    public ManageInterface(String userName, String hostIpAddress) {
        this.hostIpAddress = hostIpAddress;
        this.userName = userName;
    }

    public void init() {
        JPanel gradeQueryPanel = new GradeQueryPage(hostIpAddress).init();
        jFrame = new JFrame(userName + ",欢迎你！");

        jTabbedPane = new JTabbedPane();
        jTabbedPane.setTabPlacement(JTabbedPane.NORTH);
        jTabbedPane.addTab("班级管理", classManageSplitPane);
        jTabbedPane.addTab("成绩管理", gradeManageSplitPane);
        jTabbedPane.addTab("成绩查询", gradeQueryPanel);
        jTabbedPane.addTab("退出系统", new ExitPage(new ImageIcon("images/DrawingIllustration.jpg").getImage()));
        jTabbedPane.setUI(new MyTabbedPaneUI("#FFFAFA", "#98F5FF"));


        //处理班级管理分割组件
        BackGroundPanel classLeftPanel = new BackGroundPanel(new ImageIcon("images\\illustration_jogging.png").getImage());
        classManageSplitPane.setLeftComponent(classLeftPanel);

        Box leftBox = Box.createVerticalBox();
        JLabel classChoice = new JLabel("选择班级:");
        JLabel majorChoice = new JLabel("选择专业:");
        JLabel facultyChoice = new JLabel("选择院系:");
        JButton addStudent = new JButton("添加学生");
        JButton deleteStudent = new JButton("删除学生信息");
        JButton updateStudent = new JButton("更新学生信息");
        Box btnBox = Box.createHorizontalBox();
        btnBox.add(addStudent);
        btnBox.add(Box.createHorizontalStrut(10));
        btnBox.add(deleteStudent);
        btnBox.add(Box.createHorizontalStrut(10));
        btnBox.add(updateStudent);


        JComboBox<String> majorBox = new JComboBox<>();
        JComboBox<String> classBox = new JComboBox<>();
        JComboBox<String> facultyBox = new JComboBox<>(RandomAdd.getFacultyArrays());
        facultyBox.setSelectedIndex(0);
        //复用
        String selectedFaculty = facultyBox.getSelectedItem().toString();
        String[] majorsAdd = RandomAdd.MAJOR.get(selectedFaculty);
        for (String major : majorsAdd) {
            majorBox.addItem(major);
        }
        majorBox.setSelectedIndex(0);
        String selectedMajor = majorBox.getSelectedItem().toString();
        Query query = new Query(hostIpAddress);
        query.setDatabaseName("sams");
        query.setSQL("select distinct class from student where major=" + "'" + selectedMajor + "'");
        String[][] result = query.getRecord();
        for (int i = 0; i < result.length; i++) {
            classBox.addItem(selectedMajor + result[i][0] + "班");
        }

        classBox.setSelectedIndex(0);
        int selectedClass = classBox.getSelectedIndex() + 1;
        String sql = "select sno, sname, gender, bornday from student where major=" + "'" + selectedMajor + "' and class=" + selectedClass;
        query.setSQL(sql);
        String[] columns = new String[]{"学号", "姓名", "性别", "出生日期"};
        JTable studentTable = new JTable(query.getVectorRecord(), new Vector<String>(java.util.List.of(columns)));
        JTableHeader studentTableHead = studentTable.getTableHeader();
        studentTableHead.setPreferredSize(new Dimension(studentTableHead.getWidth(), 35));// 设置表头大小
        studentTableHead.setFont(new Font("楷体", Font.BOLD, 20));// 设置表格字体
        DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
        defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
        studentTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
        studentTable.setRowHeight(24);  //设置行高
        studentTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);// 以下设置表格列宽
        TableColumn column;
        column = studentTable.getColumnModel().getColumn(0);
        column.setPreferredWidth(60);

        JScrollPane jScrollPane = new JScrollPane(studentTable);
        jScrollPane.setPreferredSize(new Dimension(720, 480));
        studentTablePanel.setLayout(new BorderLayout());
        studentTablePanel.add(jScrollPane);
        studentTablePanel.add(btnBox, BorderLayout.SOUTH);
        classManageSplitPane.setRightComponent(studentTablePanel);

        Box classChoiceBox = Box.createHorizontalBox();
        Box majorChoiceBox = Box.createHorizontalBox();
        Box facultyChoiceBox = Box.createHorizontalBox();
        classChoiceBox.add(classChoice);
        classChoiceBox.add(Box.createHorizontalStrut(10));
        classChoiceBox.add(classBox);
        majorChoiceBox.add(majorChoice);
        majorChoiceBox.add(Box.createHorizontalStrut(10));
        majorChoiceBox.add(majorBox);
        facultyChoiceBox.add(facultyChoice);
        facultyChoiceBox.add(Box.createHorizontalStrut(10));
        facultyChoiceBox.add(facultyBox);
        leftBox.add(Box.createVerticalStrut(50));
        leftBox.add(facultyChoiceBox);
        leftBox.add(Box.createVerticalStrut(50));
        leftBox.add(majorChoiceBox);
        leftBox.add(Box.createVerticalStrut(50));
        leftBox.add(classChoiceBox);
        classLeftPanel.add(leftBox);
        //班级管理区域左侧组件的事件处理
        facultyBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                switch (e.getStateChange()) {
                    case ItemEvent.SELECTED:
                        majorBox.removeAllItems();
                        String selectedFaculty = facultyBox.getSelectedItem().toString();
                        String[] majorsAdd = RandomAdd.MAJOR.get(selectedFaculty);
                        for (String major : majorsAdd) {
                            majorBox.addItem(major);
                        }
                        break;
                    case ItemEvent.DESELECTED:
                        break;
                }
            }
        });

        majorBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    classBox.removeAllItems();
                    String selectedMajor = majorBox.getSelectedItem().toString();
                    Query query = new Query(hostIpAddress);
                    query.setDatabaseName("sams");
                    query.setSQL("select distinct class from student where major=" + "'" + selectedMajor + "'");
                    String[][] result = query.getRecord();
                    for (String[] strings : result) {
                        classBox.addItem(selectedMajor + strings[0] + "班");
                    }
                }
            }
        });

        classBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String selectedMajor = majorBox.getSelectedItem().toString();
                    int selectedClass = classBox.getSelectedIndex() + 1;
                    JTable newStudentTable = getNewStudentTable(selectedMajor, selectedClass);
                    newStudentTable.setEnabled(false);
                    JScrollPane jScrollPane2 = new JScrollPane(newStudentTable);
                    jScrollPane2.setPreferredSize(new Dimension(720, 480));
                    JPanel newStudentTablePanel = new JPanel();
                    newStudentTablePanel.setLayout(new BorderLayout());
                    newStudentTablePanel.add(jScrollPane2);
                    newStudentTablePanel.add(btnBox, BorderLayout.SOUTH);
                    classManageSplitPane.setRightComponent(newStudentTablePanel);
                }
            }
        });

        addStudent.addActionListener((ActionEvent e) -> {
            new StudentAddPage(hostIpAddress).init();
        });

        deleteStudent.addActionListener((ActionEvent e) -> {
            String sno = null;
            sno = JOptionPane.showInputDialog("请输入要删除的学生学号：");
            if (sno.length() != 0 && isSnoExists(sno)) {
                String uri =
                        "jdbc:mysql://" + hostIpAddress + ":3306/" +
                                "sams" + "?useSSL=true&characterEncoding=utf-8";
                try {
                    Connection connection = DriverManager.getConnection(uri, "zhang", "123456");
                    Statement statement = connection.createStatement();
                    statement.execute("delete from student where sno=" + sno);
                    statement.close();
                    JOptionPane.showMessageDialog(jFrame, "删除成功");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            } else if (sno.length() == 0) {
                JOptionPane.showMessageDialog(jFrame, "请输入学号！");
            } else JOptionPane.showMessageDialog(jFrame, "此学号不存在");
        });

        updateStudent.addActionListener((ActionEvent e) -> {
            String sno = JOptionPane.showInputDialog("请输入要进行信息修改的学生学号：");
            if (sno.length() != 0 && isSnoExists(sno)) {
                new StudentUpdatePage(hostIpAddress, sno).init();
            } else if (sno.length() == 0) {
                JOptionPane.showMessageDialog(jFrame, "请输入学号！");
            } else JOptionPane.showMessageDialog(jFrame, "此学号不存在");
        });


        //处理成绩管理页面的分割组件
        BackGroundPanel gradeLeftPanel = new BackGroundPanel(new ImageIcon("images/illustration_weight lifting.png").getImage());
        Box leftBox2 = Box.createVerticalBox();
        JLabel classChoice2 = new JLabel("选择班级:");
        JLabel majorChoice2 = new JLabel("选择专业:");
        JLabel facultyChoice2 = new JLabel("选择院系:");

        JComboBox<String> majorBox2 = new JComboBox<>();
        JComboBox<String> classBox2 = new JComboBox<>();
        JComboBox<String> facultyBox2 = new JComboBox<>(RandomAdd.getFacultyArrays());
        facultyBox2.setSelectedIndex(0);
        //复用
        String selectedFaculty2 = facultyBox.getSelectedItem().toString();
        String[] majorsAdd2 = RandomAdd.MAJOR.get(selectedFaculty2);
        for (String major : majorsAdd2) {
            majorBox2.addItem(major);
        }
        majorBox2.setSelectedIndex(0);
        String selectedMajor2 = majorBox2.getSelectedItem().toString();
        Query query2 = new Query(hostIpAddress);
        query2.setDatabaseName("sams");
        query2.setSQL("select distinct class from student where major=" + "'" + selectedMajor2 + "'");
        String[][] result2 = query2.getRecord();
        for (int i = 0; i < result2.length; i++) {
            classBox2.addItem(selectedMajor2 + result2[i][0] + "班");
        }


        gradeManageSplitPane.setRightComponent(new GradeManagePanel(hostIpAddress, "计算机科学与技术", "01").init());
        Box classChoiceBox2 = Box.createHorizontalBox();
        Box majorChoiceBox2 = Box.createHorizontalBox();
        Box facultyChoiceBox2 = Box.createHorizontalBox();
        classChoiceBox2.add(classChoice2);
        classChoiceBox2.add(Box.createHorizontalStrut(10));
        classChoiceBox2.add(classBox2);
        majorChoiceBox2.add(majorChoice2);
        majorChoiceBox2.add(Box.createHorizontalStrut(10));
        majorChoiceBox2.add(majorBox2);
        facultyChoiceBox2.add(facultyChoice2);
        facultyChoiceBox2.add(Box.createHorizontalStrut(10));
        facultyChoiceBox2.add(facultyBox2);
        leftBox2.add(Box.createVerticalStrut(50));
        leftBox2.add(facultyChoiceBox2);
        leftBox2.add(Box.createVerticalStrut(50));
        leftBox2.add(majorChoiceBox2);
        leftBox2.add(Box.createVerticalStrut(50));
        leftBox2.add(classChoiceBox2);

        //成绩管理区域左侧组件的事件处理
        facultyBox2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                switch (e.getStateChange()) {
                    case ItemEvent.SELECTED:
                        majorBox2.removeAllItems();
                        String selectedFaculty2 = facultyBox2.getSelectedItem().toString();
                        String[] majorsAdd2 = RandomAdd.MAJOR.get(selectedFaculty2);
                        for (String major : majorsAdd2) {
                            majorBox2.addItem(major);
                        }
                        break;
                    case ItemEvent.DESELECTED:
                        break;
                }
            }
        });

        majorBox2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    classBox2.removeAllItems();
                    String selectedMajor2 = majorBox2.getSelectedItem().toString();
                    Query query = new Query(hostIpAddress);
                    query.setDatabaseName("sams");
                    query.setSQL("select distinct class from student where major=" + "'" + selectedMajor2 + "'");
                    String[][] result = query.getRecord();
                    for (String[] strings : result) {
                        classBox2.addItem(selectedMajor2 + strings[0] + "班");
                    }
                }
            }
        });

        classBox2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String major = majorBox2.getSelectedItem().toString();
                    String classNumber = Integer.toString(classBox2.getSelectedIndex() + 1);
                    gradeManageSplitPane.setRightComponent(new GradeManagePanel(hostIpAddress, major, classNumber).init());
                }
            }
        });
        gradeLeftPanel.add(leftBox2);
        gradeManageSplitPane.setLeftComponent(gradeLeftPanel);

        jFrame.setBounds((ScreenUtils.getScreenWidth() - WIDTH) / 2,
                (ScreenUtils.getScreenHeight() - HEIGHT) / 2, WIDTH, HEIGHT);
        jFrame.add(jTabbedPane);
        jFrame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        jFrame.setResizable(false);
        jFrame.setIconImage(new ImageIcon("images//学生信息-彩色.png").getImage());
        jFrame.pack();
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    private JTable getNewStudentTable(String major, int classNumber) {
        Query query = new Query(hostIpAddress);
        query.setDatabaseName("sams");
        query.setSQL("select sno, sname, gender, bornday from student where major=" + "'" + major + "' and class=" + classNumber);
        String[] columns = new String[]{"学号", "姓名", "性别", "出生日期"};
        JTable studentTable = new JTable(query.getVectorRecord(), new Vector<String>(java.util.List.of(columns)));
        JTableHeader studentTableHead = studentTable.getTableHeader();
        studentTableHead.setPreferredSize(new Dimension(studentTableHead.getWidth(), 35));// 设置表头大小
        studentTableHead.setFont(new Font("楷体", Font.BOLD, 20));// 设置表格字体
        DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
        defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
        studentTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
        studentTable.setRowHeight(24);  //设置行高
        studentTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);// 以下设置表格列宽
        TableColumn column;
        column = studentTable.getColumnModel().getColumn(0);
        column.setPreferredWidth(60);
        studentTable.setEnabled(false);
        return studentTable;
    }

    private boolean isSnoExists(String sno) {
        Query query = new Query(hostIpAddress);
        query.setDatabaseName("sams");
        query.setSQL("select * from student where sno=" + sno);
        String[][] result = query.getRecord();
        return result.length != 0;
    }
}
